package common.lambda.collectors;

import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * 实现一个自定义的收集器
 * https://www.cnblogs.com/webor2006/p/8342427.html
 * @param <T>
 */
public class  MySetCollector<T> implements Collector<T, Set<T>,Set<T>> {
    @Override
    public Supplier<Set<T>> supplier() {

        System.out.println("invoke Supplier");
        return HashSet::new;
    }

    @Override
    public BiConsumer<Set<T>, T> accumulator() {
        System.out.println("invoke accumulator");

        return Set<T>::add;
    }

    @Override
    public BinaryOperator<Set<T>> combiner() {
        System.out.println("invoke combiner");

        return (sets1,sets2) -> {
            sets1.addAll(sets2);
            return sets1;
        };
    }

    @Override
    public Function<Set<T>, Set<T>> finisher() {
        System.out.println("invoke finisher");

        return Function.identity();
    }

    @Override
    public Set<Characteristics> characteristics() {
        System.out.println("invoke characteristics");

        return Collections.unmodifiableSet(EnumSet.of(Characteristics.IDENTITY_FINISH,Characteristics.UNORDERED));
    }

    public static void main(String[] args) {
        List<String> strings = Arrays.asList("hello", "zhangsan", "lisi", "wangwu");

        Set<String> collect = strings.stream().collect(new MySetCollector<>());

        System.out.println(collect);
    }
}
